export default {
  //是否是数字类型
  isNum: function (data) {
    if (typeof data == "number") {
      return true;
    } else {
      return false;
    }
  },
  //是否是n位数字
  isNNum: function (data, len) {
    var Pardata = String(data);
    if (/^[0-9]*$/.test(Pardata) && Pardata.length == len) {
      return true;
    } else {
      return false;
    }
  },
  //是否是字符串
  isString: function (str) {
    if (typeof str === "string" || str instanceof String) {
      return true;
    }
    return false;
  },
  //是否是数组
  isArray: function (arg) {
    if (typeof Array.isArray === "undefined") {
      return Object.prototype.toString.call(arg) === "[object Array]";
    }
    return Array.isArray(arg);
  },
  //判断两个数组是否相等  数组里有对象就不能判断了
  arrayEqual: function (arr1, arr2) {
    if (arr1 === arr2) return true;
    if (arr1.length != arr2.length) return false;
    for (let i = 0; i < arr1.length; ++i) {
      if (arr1[i] !== arr2[i]) return false;
    }
    return true;
  },
  //是否相等 不能判断对象和数组
  isEqual: function (val1, val2) {
    if (val1 === val2) {
      return true;
    } else {
      return false;
    }
  },
  //是否是纯数字或字母
  isNoLetter: function (data) {
    if (/^[0-9a-zA-Z]*$/g.test(data)) {
      return true;
    } else {
      return false;
    }
  },
  //是否是纯小写
  isLowerCase: function (str) {
    const reg = /^[a-z]+$/;
    return reg.test(str);
  },
  //是否是纯大写
  isUpperCase: function (str) {
    const reg = /^[A-Z]+$/;
    return reg.test(str);
  },
  //是否是纯字母
  validAlphabets: function (str) {
    const reg = /^[A-Za-z]+$/;
    return reg.test(str);
  },
  //是否是手机号
  isPhone: function (data) {
    var Pardata = String(data);
    if (Pardata.length === 11 && /^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(Pardata)) {
      return true;
    } else {
      return false;
    }
  },
  //是否是身份证号
  /*
 2     功能：验证身份证号码是否有效
 3     提示信息：未输入或输入身份证号不正确！
 4     使用：isIdCard(obj)
 5     返回：0,1,2,3
 6     返回0表示身份证号码正确
 7     返回1表示非法身份证号码
 8     返回2表示非法地区
 9     返回3表示非法生日
10 */
  isIdCard: function (data) {
    var aCity = {
      11: "北京",
      12: "天津",
      13: "河北",
      14: "山西",
      15: "内蒙古",
      21: "辽宁",
      22: "吉林",
      23: "黑龙江",
      31: "上海",
      32: "江苏",
      33: "浙江",
      34: "安徽",
      35: "福建",
      36: "江西",
      37: "山东",
      41: "河南",
      42: "湖 北",
      43: "湖南",
      44: "广东",
      45: "广西",
      46: "海南",
      50: "重庆",
      51: "四川",
      52: "贵州",
      53: "云南",
      54: "西 藏",
      61: "陕西",
      62: "甘肃",
      63: "青海",
      64: "宁夏",
      65: "新疆",
      71: "台湾",
      81: "香港",
      82: "澳门",
      91: "国 外",
    };
    var iSum = 0;
    var strIDno = String(data);
    var idCardLength = strIDno.length;
    if (!/^\d{17}(\d|x)$/i.test(strIDno) && !/^\d{15}$/i.test(strIDno))
      return "身份证号不能为空"; //非法身份证号

    if (aCity[parseInt(strIDno.substr(0, 2))] == null) return "地区不正确"; // 非法地区
    // 15位身份证转换为18位
    if (idCardLength == 15) {
      var sBirthday =
        "19" +
        strIDno.substr(6, 2) +
        "-" +
        Number(strIDno.substr(8, 2)) +
        "-" +
        Number(strIDno.substr(10, 2));
      var d = new Date(sBirthday.replace(/-/g, "/"));
      var dd =
        d.getFullYear().toString() +
        "-" +
        (d.getMonth() + 1) +
        "-" +
        d.getDate();
      if (sBirthday != dd) return "生日不正确"; //非法生日
      strIDno = strIDno.substring(0, 6) + "19" + strIDno.substring(6, 15);
      strIDno = strIDno + GetVerifyBit(strIDno);
    }

    // 判断是否大于2078年，小于1900年
    var year = strIDno.substring(6, 10);
    if (year < 1900 || year > 2078) return "生日不正确"; //非法生日

    //18位身份证处理
    //在后面的运算中x相当于数字10,所以转换成a
    strIDno = strIDno.replace(/x$/i, "a");
    var sBirthday =
      strIDno.substr(6, 4) +
      "-" +
      Number(strIDno.substr(10, 2)) +
      "-" +
      Number(strIDno.substr(12, 2));
    var d = new Date(sBirthday.replace(/-/g, "/"));
    if (
      sBirthday !=
      d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate()
    )
      return "生日不正确"; //非法生日
    // 身份证编码规范验证
    for (var i = 17; i >= 0; i--)
      iSum += (Math.pow(2, i) % 11) * parseInt(strIDno.charAt(17 - i), 11);
    if (iSum % 11 != 1) return "身份证号不正确"; // 非法身份证号

    // 判断是否屏蔽身份证
    var words = new Array();
    words = new Array("11111119111111111", "12121219121212121");

    for (var k = 0; k < words.length; k++) {
      if (strIDno.indexOf(words[k]) != -1) {
        return "身份证号已屏蔽";
      }
    }

    return 0;
  },
  //是否是外链
  isExternal: function (path) {
    return /^(https?:|mailto:|tel:)/.test(path);
  },
  //是否是邮件
  validEmail: function (email) {
    const reg =
      /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return reg.test(email);
  },
  //是否是PC端
  isPC: function () {
    let userAgentInfo = navigator.userAgent;
    let Agents = [
      "Android",
      "iPhone",
      "SymbianOS",
      "Windows Phone",
      "iPad",
      "iPod",
    ];
    let flag = true;
    for (let v = 0; v < Agents.length; v++) {
      if (userAgentInfo.indexOf(Agents[v]) > 0) {
        flag = false;
        break;
      }
    }
    return flag;
  },
  // 判断是android还是ios还是web
  isDevice: function () {
    var ua = navigator.userAgent.toLowerCase();
    // ios
    if (ua.match(/iPhone\sOS/i) == "iphone os" || ua.match(/iPad/i) == "ipad") {
      return "iOS";
    }
    // android
    else if (ua.match(/Android/i) == "android") {
      return "Android";
    }
    //Web
    else {
      return "Web";
    }
  },
  //是否是微信的浏览器
  isWx: function () {
    var ua = navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == "micromessenger") {
      return true;
    } else {
      return false;
    }
  },
  //节流
  reduceExpenditure(fn, wait = 500) {
    var timer = null;
    var startTime = Date.now();
    return function () {
      var curTime = Date.now();
      var remaining = wait - (curTime - startTime);
      var context = this;
      var args = arguments;
      clearTimeout(timer);
      if (remaining <= 0) {
        fn.apply(context, args);
        startTime = Date.now();
      } else {
        timer = setTimeout(fn, remaining);
      }
    };
  },
  //防抖
  debounce(fn, delay = 500) {
    let timer = null;
    return function () {
      if (timer) {
        clearTimeout(timer);
      }
      timer = setTimeout(() => {
        fn.apply(this, arguments);
        timer = null;
      }, delay);
    };
  },
  //对象序列化
  stringfyQueryString: function (obj) {
    //对象序列化【对象转url参数】
    if (!obj) return "";
    let pairs = [];
    for (let key in obj) {
      let value = obj[key];
      if (value instanceof Array) {
        for (let i = 0; i < value.length; ++i) {
          pairs.push(
            encodeURIComponent(key + "[" + i + "]") +
              "=" +
              encodeURIComponent(value[i])
          );
        }
        continue;
      }
      pairs.push(encodeURIComponent(key) + "=" + encodeURIComponent(obj[key]));
    }
    return pairs.join("&");
  },
  //生成随机范围数字
  random: function (min, max) {
    if (arguments.length === 2) {
      return Math.floor(min + Math.random() * (max + 1 - min));
    } else {
      return null;
    }
  },
  //本地限时存储(天)
  store: {
    // 本地存储
    set: function (name, value, day) {
      // 设置
      let d = new Date();
      let time = 0;
      day = typeof day === "undefined" || !day ? 1 : day; // 时间,默认存储1天
      time = d.setHours(d.getHours() + 24 * day); // 毫秒
      localStorage.setItem(name, JSON.stringify({ data: value, time: time }));
    },
    get: function (name) {
      // 获取
      let data = localStorage.getItem(name);
      if (!data) {
        return null;
      }
      let obj = JSON.parse(data);
      if (new Date().getTime() > obj.time) {
        // 过期
        localStorage.removeItem(name);
        return null;
      } else {
        return obj.data;
      }
    },
    clear: function (name) {
      // 清空
      if (name) {
        // 删除键为name的缓存
        localStorage.removeItem(name);
      } else {
        // 清空全部
        localStorage.clear();
      }
    },
  },
  // Js获取元素样式【支持内联】 xx.getRealStyle(this.$refs.xx, "height")
  getRealStyle: function (obj, styleName) {
    var realStyle = null;
    if (obj.currentStyle) {
      realStyle = obj.currentStyle[styleName];
    } else if (window.getComputedStyle) {
      realStyle = window.getComputedStyle(obj, null)[styleName];
    }
    return realStyle;
  },
  // 复制功能
  copyTxt: function (text, fn) {
    if (typeof document.execCommand !== "function") {
      console.log("复制失败，请长按复制");
      return;
    }
    var dom = document.createElement("textarea");
    dom.value = text;
    dom.setAttribute("style", "display: block;width: 1px;height: 1px;");
    document.body.appendChild(dom);
    dom.select();
    var result = document.execCommand("copy");
    document.body.removeChild(dom);
    if (result) {
      console.log("复制成功");
      typeof fn === "function" && fn();
      return;
    }
    if (typeof document.createRange !== "function") {
      console.log("复制失败，请长按复制");
      return;
    }
    var range = document.createRange();
    var div = document.createElement("div");
    div.innerhtml = text;
    div.setAttribute("style", "height: 1px;fontSize: 1px;overflow: hidden;");
    document.body.appendChild(div);
    range.selectNode(div);
    var selection = window.getSelection();
    console.log(selection);
    if (selection.rangeCount > 0) {
      selection.removeAllRanges();
    }
    selection.addRange(range);
    document.execCommand("copy");
    typeof fn === "function" && fn();
    console.log("复制成功");
  },
  // 常用正则验证，注意type大小写
  checkStr: function (str, type) {
    switch (type) {
      case "phone": // 手机号码
        return /^1[3|4|5|6|7|8|9][0-9]{9}$/.test(str);
      case "tel": // 座机
        return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str);
      case "card": // 身份证
        return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(str);
      case "pwd": // 密码以字母开头，长度在6~18之间，只能包含字母、数字和下划线
        return /^[a-zA-Z]\w{5,17}$/.test(str);
      case "postal": // 邮政编码
        return /[1-9]\d{5}(?!\d)/.test(str);
      case "QQ": // QQ号
        return /^[1-9][0-9]{4,9}$/.test(str);
      case "email": // 邮箱
        return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);
      case "money": // 金额(小数点2位)
        return /^\d*(?:\.\d{0,2})?$/.test(str);
      case "URL": // 网址
        return /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(
          str
        );
      case "IP": // IP
        return /((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))/.test(
          str
        );
      case "date": // 日期时间
        return (
          /^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})(?:\:\d{2}|:(\d{2}):(\d{2}))$/.test(
            str
          ) || /^(\d{4})\-(\d{2})\-(\d{2})$/.test(str)
        );
      case "number": // 数字
        return /^[0-9]$/.test(str);
      case "english": // 英文
        return /^[a-zA-Z]+$/.test(str);
      case "chinese": // 中文
        return /^[\u4E00-\u9FA5]+$/.test(str);
      case "lower": // 小写
        return /^[a-z]+$/.test(str);
      case "upper": // 大写
        return /^[A-Z]+$/.test(str);
      case "HTML": // HTML标记
        return /<("[^"]*"|'[^']*'|[^'">])*>/.test(str);
      default:
        return true;
    }
  },
  // 去除空格， type:  1-所有空格  2-前后空格  3-前空格 4-后空格
  trim: function (str, type) {
    type = type || 1;
    switch (type) {
      case 1:
        return str.replace(/\s+/g, "");
      case 2:
        return str.replace(/(^\s*)|(\s*$)/g, "");
      case 3:
        return str.replace(/(^\s*)/g, "");
      case 4:
        return str.replace(/(\s*$)/g, "");
      default:
        return str;
    }
  },
  // 字符串大小写转换 type:  1:首字母大写  2：首页母小写  3：大小写转换  4：全部大写  5：全部小写
  changeCase: function (str, type) {
    type = type || 4;
    switch (type) {
      case 1:
        return str.replace(/\b\w+\b/g, function (word) {
          return (
            word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase()
          );
        });
      case 2:
        return str.replace(/\b\w+\b/g, function (word) {
          return (
            word.substring(0, 1).toLowerCase() + word.substring(1).toUpperCase()
          );
        });
      case 3:
        return str
          .split("")
          .map(function (word) {
            if (/[a-z]/.test(word)) {
              return word.toUpperCase();
            } else {
              return word.toLowerCase();
            }
          })
          .join("");
      case 4:
        return str.toUpperCase();
      case 5:
        return str.toLowerCase();
      default:
        return str;
    }
  },
  // 将阿拉伯数字翻译成中文的大写数字 type 1:是简写  2：是繁写
  numberToChinese: function (num, type) {
    let AA;
    if (type == 1) {
      AA = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十"];
    } else {
      AA = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖", "拾"];
    }
    let BB = new Array("", "十", "百", "仟", "萬", "億", "点", "");
    let a = ("" + num).replace(/(^0*)/g, "").split(".");
    let k = 0;
    let re = "";
    for (let i = a[0].length - 1; i >= 0; i--) {
      switch (k) {
        case 0:
          re = BB[7] + re;
          break;
        case 4:
          if (
            !new RegExp("0{4}//d{" + (a[0].length - i - 1) + "}$").test(a[0])
          ) {
            re = BB[4] + re;
          }
          break;
        case 8:
          re = BB[5] + re;
          BB[7] = BB[5];
          k = 0;
          break;
      }
      if (k % 4 === 2 && a[0].charAt(i + 2) !== 0 && a[0].charAt(i + 1) === 0) {
        re = AA[0] + re;
      }
      if (a[0].charAt(i) !== 0) {
        re = AA[a[0].charAt(i)] + BB[k % 4] + re;
      }
      k++;
    }
    if (a.length > 1) {
      // 加上小数部分(如果有小数部分)
      re += BB[6];
      for (let i = 0; i < a[1].length; i++) {
        re += AA[a[1].charAt(i)];
      }
    }
    if (re === "一十") {
      re = "十";
    }
    if (re.match(/^一/) && re.length === 3) {
      re = re.replace("一", "");
    }
    return re;
  },
  // 原生dom操作
  dom: {
    $: function (selector) {
      let type = selector.substring(0, 1);
      if (type === "#") {
        if (document.querySelecotor) return document.querySelector(selector);
        return document.getElementById(selector.substring(1));
      } else if (type === ".") {
        if (document.querySelecotorAll)
          return document.querySelectorAll(selector);
        return document.getElementsByClassName(selector.substring(1));
      } else {
        return document[
          "querySelectorAll" ? "querySelectorAll" : "getElementsByTagName"
        ](selector);
      }
    },
    hasClass: function (ele, name) {
      /* 检测类名 */ return ele.className.match(
        new RegExp("(\\s|^)" + name + "(\\s|$)")
      );
    },
    addClass: function (ele, name) {
      /* 添加类名 */ if (!this.hasClass(ele, name)) ele.className += " " + name;
    },
    removeClass: function (ele, name) {
      /* 删除类名 */ if (this.hasClass(ele, name)) {
        let reg = new RegExp("(\\s|^)" + name + "(\\s|$)");
        ele.className = ele.className.replace(reg, "");
      }
    },
    replaceClass: function (ele, newName, oldName) {
      /* 替换类名 */ this.removeClass(ele, oldName);
      this.addClass(ele, newName);
    },
    siblings: function (ele) {
      /* 获取兄弟节点 */ console.log(ele.parentNode);
      let chid = ele.parentNode.children,
        eleMatch = [];
      for (let i = 0, len = chid.length; i < len; i++) {
        if (chid[i] !== ele) {
          eleMatch.push(chid[i]);
        }
      }
      return eleMatch;
    },
    getByStyle: function (obj, name) {
      /* 获取行间样式属性 */
      if (obj.currentStyle) {
        return obj.currentStyle[name];
      } else {
        return getComputedStyle(obj, false)[name];
      }
    },
    domToStirng: function (htmlDOM) {
      /* DOM转字符串 */ var div = document.createElement("div");
      div.appendChild(htmlDOM);
      return div.innerHTML;
    },
    stringToDom: function (htmlString) {
      /* 字符串转DOM */ var div = document.createElement("div");
      div.innerHTML = htmlString;
      return div.children[0];
    },
  },
  //图片或图片地址url转为base64
  getBase64: {
    //图片转base64，使用：xx.getBase64.toBase64(this.$refs.xx)
    toBase64(img) {
      const canvas = document.createElement("canvas"); //创建一个canvas元素
      const ctx = canvas.getContext("2d");
      canvas.width = img.width; //把当前url对应的图片的宽度赋予canvas
      canvas.height = img.height; //把当前url对应的图片的高度赋予canvas
      img.setAttribute("crossOrigin", "Anonymous");
      ctx.drawImage(img, 0, 0, canvas.width, canvas.height); //在画布上一比一的画出img
      const base64 = canvas.toDataURL("image/jpeg"); //调用canvas的toDataURL获取.jpg的base64数据
      return base64;
    },
    //url转base64,
    getImageUrlBase64(url) {
      const img = new Image();
      img.crossOrigin = "anonymous"; //处理跨域，后端也要设置跨域处理才行
      img.src = url;
      img.onload = () => {
        return toBase64(img);
      };
    },
  },
  //base64图片下载功能
  downloadFile: function (base64, fileName) {
    //base64图片下载功能
    let base64ToBlob = function (code) {
      let parts = code.split(";base64,");
      let contentType = parts[0].split(":")[1];
      let raw = window.atob(parts[1]);
      let rawLength = raw.length;
      let uInt8Array = new Uint8Array(rawLength);
      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
      }
      return new Blob([uInt8Array], { type: contentType });
    };
    let aLink = document.createElement("a");
    let blob = base64ToBlob(base64); //
    // new Blob([content]);
    let evt = document.createEvent("HTMLEvents");
    evt.initEvent("click", true, true);
    //initEvent不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
    aLink.download = fileName;
    aLink.href = URL.createObjectURL(blob);
    aLink.click();
  },
  //H5软键盘缩回、弹起回调。  放在mounted生命周期函数中调用
  h5Resize: function (downCb, upCb) {
    //当软件键盘弹起会改变当前 window.innerHeight，监听这个值变化 [downCb 缩回的回调,upCb 当软键盘弹起的回调]
    var clientHeight = window.innerHeight;
    downCb = typeof downCb === "function" ? downCb : function () {};
    upCb = typeof upCb === "function" ? upCb : function () {};
    window.addEventListener("resize", () => {
      var height = window.innerHeight;
      if (height === clientHeight) {
        downCb();
      }
      if (height < clientHeight) {
        upCb();
      }
    });
  },
  //数组去重,不能清除数组里的对象
  arrayDup(arr) {
    return Array.from(new Set(arr));
  },
  //滚动加载，只能用在pc端。 放在mounted生命周期函数中调用
  scrollListen(func) {
    window.addEventListener("scroll", function () {
      const clientHeight = document.documentElement.clientHeight;
      const scrollTop = document.documentElement.scrollTop;
      const scrollHeight = document.documentElement.scrollHeight;
      if (
        clientHeight + scrollTop >= scrollHeight &&
        typeof func == "function"
      ) {
        func();
      }
    });
  },
  /*日期格式化 用法： parseTime("2020/12/26 12:12:20", "{y}-{m}-{d} {h}:{i}:{s} 星期{a}")
  time的值可以是时间戳，new Date()对象，字符串形式的时间格式，patterns是显示格式   */
  parseTime(time, pattern) {
    if (arguments.length === 0 || !time) {
      return null;
    }
    const format = pattern || "{y}-{m}-{d} {h}:{i}:{s}";
    let date;
    if (typeof time === "object") {
      date = time;
    } else {
      if (typeof time === "string" && /^[0-9]+$/.test(time)) {
        time = parseInt(time);
      } else if (typeof time === "string") {
        time = time
          .replace(new RegExp(/-/gm), "/")
          .replace("T", " ")
          .replace(new RegExp(/\.[\d]{3}/gm), "");
      }
      if (typeof time === "number" && time.toString().length === 10) {
        time = time * 1000;
      }
      date = new Date(time);
    }
    const formatObj = {
      y: date.getFullYear(),
      m: date.getMonth() + 1,
      d: date.getDate(),
      h: date.getHours(),
      i: date.getMinutes(),
      s: date.getSeconds(),
      a: date.getDay(),
    };
    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
      let value = formatObj[key];
      // Note: getDay() returns 0 on Sunday
      if (key === "a") {
        return ["日", "一", "二", "三", "四", "五", "六"][value];
      }
      if (result.length > 0 && value < 10) {
        value = "0" + value;
      }
      return value || 0;
    });
    return time_str;
  },
  /* 显示过去的时间，time参数是时间戳，
    option 是parseTime的参数"{y}-{m}-{d} {h}:{i}:{s}" */
  formatTime(time, option) {
    if (("" + time).length === 10) {
      time = parseInt(time) * 1000;
    } else {
      time = +time;
    }
    const d = new Date(time);
    const now = Date.now();

    const diff = (now - d) / 1000;

    if (diff < 30) {
      return "刚刚";
    } else if (diff < 3600) {
      // less 1 hour
      return Math.ceil(diff / 60) + "分钟前";
    } else if (diff < 3600 * 24) {
      return Math.ceil(diff / 3600) + "小时前";
    } else if (diff < 3600 * 24 * 2) {
      return "1天前";
    }
    if (option) {
      return parseTime(time, option);
    } else {
      return (
        d.getMonth() +
        1 +
        "月" +
        d.getDate() +
        "日" +
        d.getHours() +
        "时" +
        d.getMinutes() +
        "分"
      );
    }
  },
  /* 添加日期范围 这个是针对于有日期搜索范围的列表搜索框，params是其他的搜索条件的对象
dateRange是日期搜索框的值，propName是传输字段不符合时，你可以自己再定义*/
  addDateRange(params, dateRange, propName) {
    let search = params;
    search.params =
      typeof search.params === "object" &&
      search.params !== null &&
      !Array.isArray(search.params)
        ? search.params
        : {};
    dateRange = Array.isArray(dateRange) ? dateRange : [];
    if (typeof propName === "undefined") {
      search.params["beginTime"] = dateRange[0];
      search.params["endTime"] = dateRange[1];
    } else {
      search.params["begin" + propName] = dateRange[0];
      search.params["end" + propName] = dateRange[1];
    }
    return search;
  },
  /* 我自己再定义一个，去掉params，所有字段都在对象最外层，起始时间和结束时间,这两字段都可以自己定义*/
  addDateRangeSelf(params, dateRange, beginName, endName) {
    let search = params;
    dateRange = Array.isArray(dateRange) ? dateRange : [];
    if (
      typeof beginpropName === "undefined" ||
      typeof endpropName === "undefined"
    ) {
      search["beginTime"] = dateRange[0];
      search["endTime"] = dateRange[1];
    } else {
      search[beginName] = dateRange[0];
      search[endName] = dateRange[1];
    }
    console.log(search, 444444);
    return search;
  },
  // 转换字符串，undefined,null等转化为""
  parseStrEmpty(str) {
    if (!str || str == "undefined" || str == "null") {
      return "";
    }
    return str;
  },
  /** 构造树型结构数据 ,data 数据源*/
  handleTree(data, id, parentId, children) {
    let config = {
      id: id || "id",
      parentId: parentId || "parentId",
      childrenList: children || "children",
    };

    var childrenListMap = {};
    var nodeIds = {};
    var tree = [];

    for (let d of data) {
      let parentId = d[config.parentId];
      if (childrenListMap[parentId] == null) {
        childrenListMap[parentId] = [];
      }
      nodeIds[d[config.id]] = d;
      childrenListMap[parentId].push(d);
    }

    for (let d of data) {
      let parentId = d[config.parentId];
      if (nodeIds[parentId] == null) {
        tree.push(d);
      }
    }

    for (let t of tree) {
      adaptToChildrenList(t);
    }

    function adaptToChildrenList(o) {
      if (childrenListMap[o[config.id]] !== null) {
        o[config.childrenList] = childrenListMap[o[config.id]];
      }
      if (o[config.childrenList]) {
        for (let c of o[config.childrenList]) {
          adaptToChildrenList(c);
        }
      }
    }
    return tree;
  },
  /* 数组去重，只能单纯的去掉外层重复的数据，如有对象包着就不能去重 */
  uniqueArr(arr) {
    return Array.from(new Set(arr));
  },
  //数组里不包含对象，就去除掉数组里没有意义的值，得到新数组
  cleanArray(actual) {
    const newArray = [];
    for (let i = 0; i < actual.length; i++) {
      if (actual[i]) {
        newArray.push(actual[i]);
      }
    }
    return newArray;
  },
  //把链接里传的参数，提成一个对象
  //url实例："https://www.runoob.com/jsref.html?id=444&name=张三"
  getQueryObject(url) {
    url = url == null ? window.location.href : url;
    const search = url.substring(url.lastIndexOf("?") + 1);
    const obj = {};
    const reg = /([^?&=]+)=([^?&=]*)/g;
    search.replace(reg, (rs, $1, $2) => {
      const name = decodeURIComponent($1);
      let val = decodeURIComponent($2);
      val = String(val);
      obj[name] = val;
      return rs;
    });
    return obj;
  },
  // 数据合并
  //对象里的单独属性，不管套几层，都是参数2修改参数1的内容，保留参数1多余的属性
  //对象里的数组，不管套几层，都是参数2覆盖参数1的数组，不保留参数1多出的数组
  //在数组中，都是参数2替换掉参数1的，除非参数1比参数2多，或者参数1对象里的属性，参数2没有
  //用法：一，数组之间，2替换1。
  //二,对象之间进行合并，对象里有数组，2替换1，而且不保留1多出的数组
  mergeRecursive(source, target) {
    for (var p in target) {
      try {
        if (target[p].constructor == Object) {
          source[p] = mergeRecursive(source[p], target[p]);
        } else {
          source[p] = target[p];
        }
      } catch (e) {
        source[p] = target[p];
      }
    }
    return source;
  },
};
